# pylint: disable-msg=E1101
"""
@author: Sergiy Tsymbalyuk
"""

import logging

from pylons import tmpl_context as c, request
from pylons.i18n import lazy_ugettext as _

from repoze.what.plugins.pylonshq import ControllerProtector
from repoze.what.predicates import not_anonymous

from chowa.lib.base import BaseController, render, Session
from chowa.lib.site.navigation import Tab
from chowa.lib.site.messaging import send_message
from chowa.model.site import Message, Receipt
from chowa.model.auth import User

log = logging.getLogger(__name__)

@ControllerProtector(not_anonymous())
class MessagingController(BaseController):
    def send(self, id):
        me = request.environ.get('repoze.who.identity')['user']
        c.recipient = Session.query(User).get(id)
        query = Session.query(Receipt).join(Message)
        query = query.filter(Message.sender_id == id)
        query = query.filter(Receipt.recipient_id == me.id)
        query = query.filter(Receipt.is_read == False)
        c.messages = query.all()
        if request.method == 'POST':
            text = request.POST.get('text')
            send_message(text, me.id, id)
            return 'hello'
        return render('/social/messaging/send_form.html')
    
    def attention(self):
        if request.method == 'POST':
            if request.POST.get('reply'):
                return ''
            if request.POST.get('close'):
                msg_ids = [m[7:] for m in request.POST if m.startswith('message')]
                query = Session.query(Receipt).filter(Receipt.id.in_(msg_ids))
                query.update({'is_read': True}, synchronize_session=False)
                return ''
        return 'hello'
